package com.export.export.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class ExcelUtil {

    private File file;
    private FileOutputStream fos;
    private SXSSFWorkbook workbook;
    private SXSSFSheet sheet;

    public ExcelUtil(String filePath,String sheetName) throws Exception {
        this.file = new File(filePath);
        fos = new FileOutputStream(this.file);
        workbook = new SXSSFWorkbook();
        sheet= workbook.createSheet();
        workbook.setSheetName(0,sheetName);
    }


    public <T> void createFile(List<T> list, Function<T,?> ...functions) throws Exception {
        for (int i = 0; i < list.size(); i++) {
            SXSSFRow row = sheet.createRow(i);
            for (int j = 0; j < functions.length; j++) {
                SXSSFCell cell = row.createCell(j, CellType.STRING);
                cell.setCellValue(functions[j].apply(list.get(i))==null?"":functions[j].apply(list.get(i)).toString());
            }
        }

        workbook.write(fos);
        fos.flush();
        fos.close();
    }


    public static void main(String[] args) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil("D://dd.xlsx","dd");
        List<God> list = new ArrayList<>();
        God god = new God("999","10");
        God god1 = new God("888","100");
        list.add(god);
        list.add(god1);
        excelUtil.createFile(list,God::getAge,God::getName);
    }


}

class God{

    private String name;
    private String age;

    public God(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
